package com.itbaizhan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itbaizhan.domain.Stock;
import com.itbaizhan.domain.TxLog;
import com.itbaizhan.mapper.TxLogMapper;
import com.itbaizhan.service.StockService;
import com.itbaizhan.mapper.StockMapper;
import com.itbaizhan.tx.TxMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
* @author 13487
* @description 针对表【stock】的数据库操作Service实现
* @createDate 2024-04-23 14:22:15
*/
@Service
public class StockServiceImpl implements StockService{

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private TxLogMapper txLogMapper;

    @Override
    public void decreaseStock(TxMessage txMessage) {
        TxLog txLog = txLogMapper.selectById(txMessage.getTxNo());
        if (txLog != null){
            return;
        }

        QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id",txMessage.getProductId());
        Stock stock = stockMapper.selectOne(queryWrapper);
        if (stock != null && stock.getTotalCount() >= txMessage.getPayCount()){
            stock.setTotalCount(stock.getTotalCount() - txMessage.getPayCount());
            stockMapper.updateById(stock);
        } else {
            throw new RuntimeException("库存不足");
        }

        TxLog txLog1 = new TxLog();
        txLog1.setTxNo(txMessage.getTxNo());
        txLog1.setCreateTime(new Date());

        txLogMapper.insert(txLog1);
    }
}




